<template>
  <!-- 物料检验标准 -->
  <div class="page-container">
    <div class="handoff">
      <div
        :class="{ selected: item.value == tagVal }"
        :key="item.value"
        v-for="item in tagList"
        @click="tagHandle(item)"
      >
        {{ item.label }}
      </div>
    </div>
    <div class="common-content-wrap" v-show="tagVal == 'material'">
      <TrTable
        ref="trTable"
        isNeedSelection
        isNeedIndex
        :btnList="btnList"
        :total="totalNum"
        v-model="searchParams"
        :searchShowList="searchShowList"
        :searchHideList="searchHideList"
        :tableColumn="tableColumn"
        requestName="searchHandle"
        :tableData="materialTableData"
        @materialAdd="materialAddFun"
        @materialEnable="materialUpdateStatus(2)"
        @materialStop="materialUpdateStatus(3)"
        @export="exportHandle"
        @delRowMaterial="delRowMaterial"
        @editRowMaterial="editRowMaterial"
        @copyRowMaterial="copyRowMaterial"
        @viewRowMaterial="viewRowMaterial"
      />
      <TrEditPopup
        v-model="isShowEdit"
        :width="1227"
        :title="checkTitle"
        :valueObj.sync="formObj"
        :formData="formData"
        :list="popupList"
        :footerList="footerAddList"
        @close="addClose"
        @save="materialSave(2)"
        @temporary="materialSave(1)"
      >
        <template #table="scope">
          <div class="table-edit-wrap">
            <div class="item-title">
              <div class="title-icon"></div>
              <div class="item-name">{{ scope.label }}</div>
            </div>
            <TrTable
              isPopup
              slotStart
              isNeedIndex
              ref="treeTable"
              v-model="dialogParams"
              :btnList="materialAddbtnList"
              :tableColumn="tableAddColumn"
              :tableData="tableAddDataList"
              requestName="dialogHandle"
              :isNeedPagination="true"
              :total="dialogTotal"
              @materialTreeAdd="materialTreeAdd"
              @delRowMaterialAdd="delRowMaterialAdd"
              @editRowMaterialAdd="editRowMaterialAdd"
            />
          </div>
        </template>
      </TrEditPopup>
      <!-- 嵌套新增弹框 -->
      <TrLayout
        v-model="isShowEditInlay"
        :title="inlayCheckTitle"
        :isNeedFooter="true"
        :width="480"
        @close="inlayClose"
        @confrim="confrimHandle"
      >
        <div class="edit-list-wrap">
          <div class="edit-list-left">
            <template v-for="(item, index) in inlayPopupList">
              <div
                v-show="item.isShow"
                class="edit-item-wrap"
                :key="index"
                :style="{ width: item.width + '%' }"
                :class="[{ unNeed: item.isNeed === false }]"
              >
                <div class="edit-label" :style="{ width: '80px' }">
                  <div class="edit-text">
                    <span class="before">
                      {{ item.label }}
                    </span>
                  </div>
                </div>
                <div
                  class="edit-item-right"
                  :class="{ errorStatus: item.errorStatus }"
                >
                  <div class="edit-error-label">
                    {{ item.currentErrorLabel }}
                  </div>
                  <template v-if="item.type == 'input'">
                    <el-input
                      v-model="inlayForm[item.id]"
                      :placeholder="`请输入${item.label}`"
                      :maxlength="item.maxlength"
                      :type="item.inputType || 'text'"
                      :max="item.max"
                      :min="item.min"
                      :disabled="item.disabled"
                      @blur="changeVerify(item.id, item)"
                    ></el-input>
                  </template>
                  <template v-if="item.type == 'select'">
                    <el-select
                      v-model="inlayForm[item.id]"
                      :filterable="item.filterable"
                      :multiple="item.multiple"
                      :placeholder="item.placeholder || `请选择`"
                      :disabled="item.disabled"
                    >
                      <el-option
                        v-for="(citem, cindex) in item.list"
                        :key="cindex"
                        :label="citem.label"
                        :value="citem.value"
                      >
                      </el-option>
                    </el-select>
                  </template>
                  <template v-if="item.type == 'radio'">
                    <el-radio-group
                      v-model="inlayForm[item.id]"
                      v-removeAriaHidden
                    >
                      <el-radio
                        v-for="rItem in item.list"
                        :key="rItem.value"
                        :label="rItem.value"
                        >{{ rItem.label }}</el-radio
                      >
                    </el-radio-group>
                  </template>
                  <template v-if="item.type == 'loadselect'">
                    <TrLoadSelect
                      v-model="inlayForm[item.id]"
                      :requestObj="item.requestObj"
                      :ftObject="item"
                      :defaultParams="item.defaultParams"
                      :disabled="
                        item.disabled !== undefined ? item.disabled : false
                      "
                      :outSelectLabel="item.selectedLabel"
                      :isSaveLoad="item.isSaveLoad"
                      :searchPlaceholder="item.searchPlaceholder"
                      @change="changeSelectHandle(item, $event)"
                    />
                  </template>
                  <template v-if="item.type == 'interval'">
                    <div class="edit-interval">
                      <el-input
                        v-model="inlayForm[item.bottomProp]"
                        placeholder="数值下限"
                        :maxlength="item.maxlength"
                        :type="item.inputType || 'text'"
                        :max="item.max"
                        :min="item.min"
                        :disabled="item.disabled"
                      ></el-input>
                      <span class="lever"></span>
                      <el-input
                        v-model="inlayForm[item.topProp]"
                        placeholder="数值上限"
                        :maxlength="item.maxlength"
                        :type="item.inputType || 'text'"
                        :max="item.max"
                        :min="item.min"
                        :disabled="item.disabled"
                      ></el-input>
                    </div>
                  </template>
                </div>
              </div>
            </template>
          </div>
          <div class="edit-list-right"></div>
        </div>
      </TrLayout>
      <TrDetail
        v-model="isShowDetailPopup"
        statusModel="hidden"
        :leftList="detailList"
        :detailData="detailData"
        :footerList="footerList"
        :width="1227"
        @close="addClose"
      >
        <template #projectNameTable>
          <TrTable
            isPopup
            isNeedIndex
            isNeedPagination
            v-model="dialogParams"
            requestName="detailHandle"
            :total="dialogTotal"
            :tableData="tableAddData"
            :tableColumn="detailTableColumn"
          />
        </template>
      </TrDetail>
    </div>
    <div class="common-content-wrap" v-show="tagVal == 'standard'">
      <TrTable
        ref="trStandardTable"
        isNeedSelection
        isNeedIndex
        :btnList="standardBtnList"
        :total="standardTotal"
        v-model="standardSearchParams"
        :searchShowList="standardSearchShowList"
        :searchHideList="standardSearchHideList"
        :tableColumn="standardTableColumn"
        requestName="standardSearchHandle"
        :tableData="standardTableData"
        @standardAdd="standardIsShowEdit = true"
        @standardEnable="standardUpdateStatus(1)"
        @standardStop="standardUpdateStatus(0)"
        @export="standardExportHandle"
        @standardDelRow="standardDelRow"
      />
      <TrEditPopup
        ref="standardRef"
        v-model="standardIsShowEdit"
        :width="480"
        title="新增"
        :labelWidth="112"
        :valueObj.sync="standardFormObj"
        :formData="standardFormData"
        :relationList="relationList"
        :list="standardPopupList"
        @close="standardIsShowEdit = false"
        @confrim="standardConfrimHandle"
      />
    </div>
  </div>
</template>

<script>
import {
  getList,
  getStandardList,
  materialSave,
  standardMaterialSave,
  materialUpdateStatus,
  materialDelete,
  standardMaterialDelete,
  standardUpdateStatus,
  getDialogPage,
  dialogSave,
  dialogUpdate,
  dialogDelete,
  dialogAddUpdate,
  getDialogCopy,
} from "@/api/baseCode/materialInspectionStandard.js";
import enumData from "@/utils/enumCode.js";

import TrTable from "@/components/Tr-table/Tr-table.vue";
import TrDetail from "@/components/Tr-detail/Tr-detail.vue";
import TrEditPopup from "@/components/Tr-edit/Tr-edit-popup.vue";
import TrLayout from "@/components/Tr-layout/Tr-layout.vue";
import TrLoadSelect from "@/components/Tr-load/Tr-load.vue";

export default {
  components: {
    TrTable,
    TrDetail,
    TrEditPopup,
    TrLayout,
    TrLoadSelect,
  },
  name: "MaterialInspectionStandard",
  data: () => ({
    tagVal: "material",
    tagList: [
      { label: "物料检验标准", value: "material" },
      { label: "检验标准与物料", value: "standard" },
    ],
    // 嵌套弹框-start
    isShowEditInlay: false,
    inlayCheckTitle: "新增",
    currentType: "add",
    inlayFormData: {},
    inlayForm: {
      projectName: null,
      unitCode: null,
      testType: 2,
      standardValue: null,
      valueUpper: null,
      valueLower: null,
    },
    inlayPopupList: [
      {
        id: "projectName",
        label: "检验项目",
        isShow: true,
        type: "input",
        width: 100,
        currentErrorLabel: "请输入检验项目",
        errorStatus: false,
      },
      {
        id: "unitCode",
        label: "单位",
        type: "loadselect",
        isShow: true,
        width: 100,
        currentErrorLabel: "请选择单位",
        errorStatus: false,
        selectedLabel: "",
        reviewLabel: "unitCode",
        isNeed: true,
        requestObj: {
          url: "/api/trio-system/unit/page",
          method: "post",
          searchKey: "unitCode",
          rlLabel: "unitCode(unitName)",
          rlValue: "id",
          resultKey: "data,data,records",
        },
      },
      {
        id: "testType",
        label: "检测类别",
        isShow: true,
        type: "radio",
        width: 100,
        list: [],
        currentErrorLabel: "请选择检测类别",
        errorStatus: false,
      },
      {
        id: "standardValue",
        label: "标准数值",
        isShow: true,
        type: "input",
        inputType: "number",
        width: 100,
        isNeed: false,
      },
      {
        id: "numValue",
        label: "数值区间",
        isShow: true,
        type: "interval",
        width: 100,
        isNeed: false,
        inputType: "number",
        min: 0,
        topProp: "valueUpper",
        bottomProp: "valueLower",
      },
    ],
    // 嵌套弹框 - end

    // 物料检验标准-start
    checkTitle: "新增",
    currentHandle: "add", // add edit copy
    dialogId: "",
    searchParams: {
      updateStartTime: "",
      updateEndTime: "",
      standardCode: "",
      standardName: "",
      standardVersion: "",
      standardStatusList: [],
      createStartTime: "",
      createEndTime: "",
      current: 1,
      size: 10,
    },
    tableColumn: [
      {
        type: "text",
        label: "标准编码",
        value: "standardCode",
      },
      {
        type: "text",
        label: "标准名称",
        value: "standardName",
      },
      {
        type: "text",
        label: "标准描述",
        value: "remark",
      },
      {
        type: "text",
        label: "版本号",
        value: "standardVersion",
      },
      {
        type: "text",
        label: "生效时间",
        value: "enabledTime",
      },
      {
        type: "text",
        label: "失效时间",
        value: "disableTime",
      },
      {
        type: "text",
        label: "状态",
        value: "standardStatusName",
      },
      {
        type: "text",
        label: "创建人员",
        value: "createUserName",
      },
      {
        type: "text",
        label: "创建时间",
        value: "createTime",
      },
      {
        type: "text",
        label: "修改人员",
        value: "updateUserName",
      },
      {
        type: "text",
        label: "修改时间",
        value: "updateTime",
      },
      {
        type: "option",
        label: "操作",
        fixed: "right",
        width: 120,
        showBtnList: [
          {
            label: "查看",
            option: "viewRowMaterial",
          },
        ],
        hideBtnList: [
          { label: "编辑", option: "editRowMaterial" },
          { label: "复制", option: "copyRowMaterial" },
          { label: "删除", option: "delRowMaterial" },
        ],
      },
    ],
    materialTableData: [],
    searchHideList: [
      {
        id: "standardStatusList",
        label: "状态",
        type: "multiSelect",
        isNeed: false,
        width: 33.3,
        value: [],
        list: [],
      },
      {
        width: 33.3,
      },
      {
        startStr: "createStartTime",
        endStr: "createEndTime",
        id: "createTime",
        type: "daterange",
        width: 80,
        label: "创建时间",
        value: [],
        radio: 1,
        timePeriod: true,
      },
      {
        startStr: "updateStartTime",
        endStr: "updateEndTime",
        id: "updateTime",
        type: "daterange",
        width: 80,
        label: "修改时间",
        value: [],
        radio: -1,
        timePeriod: true,
      },
    ],
    searchShowList: [
      {
        id: "standardCode",
        type: "input",
        width: 33.3,
        label: "标准编码",
        value: "",
      },
      {
        id: "standardName",
        type: "input",
        width: 33.3,
        label: "标准名称",
        value: "",
      },
      {
        id: "standardVersion",
        type: "input",
        width: 33.3,
        label: "版本号",
        value: "",
      },
    ],
    btnList: [
      {
        label: "新增",
        option: "materialAdd",
        color: "blue",
      },
      {
        label: "启用",
        option: "materialEnable",
        color: "white",
        isRelaTable: true,
      },
      {
        label: "停用",
        option: "materialStop",
        color: "white",
        isRelaTable: true,
      },
      {
        label: "导出",
        option: "export",
        color: "white",
      },
    ],
    materialAddbtnList: [
      {
        label: "新增",
        option: "materialTreeAdd",
        color: "blue",
      },
    ],
    tableAddColumn: [
      {
        type: "text",
        label: "检验项目",
        value: "projectName",
      },
      {
        type: "text",
        label: "单位",
        value: "newNumUnit",
      },
      {
        type: "text",
        label: "标准数值",
        value: "standardValue",
      },
      {
        type: "text",
        label: "数值区间",
        value: "lowerUpper",
      },
      {
        type: "option",
        label: "操作",
        fixed: "right",
        width: 120,
        showBtnList: [
          { label: "编辑", option: "editRowMaterialAdd" },
          { label: "删除", option: "delRowMaterialAdd" },
        ],
      },
    ],
    tableAddData: [],
    tableAddDataCopy: [],
    isShowEdit: false,
    footerAddList: [
      {
        label: "取消",
        option: "close",
        color: "white",
      },
      {
        label: "暂存",
        option: "temporary",
        color: "white",
      },
      {
        label: "保存",
        option: "save",
        color: "blue",
      },
    ],
    formObj: {},
    formData: {},
    popupList: [
      {
        label: "标准编码",
        type: "input",
        width: 33.33,
        value: "",
        id: "standardCode",
        disabled: true,
        isNeed: false,
      },
      {
        label: "标准名称",
        type: "input",
        width: 33.33,
        value: "",
        id: "standardName",
      },
      {
        label: "标准描述",
        type: "input",
        width: 33.33,
        value: "",
        id: "remark",
        isNeed: false,
      },
      {
        label: "版本号",
        type: "input",
        width: 33.33,
        value: "",
        id: "standardVersion",
      },
      {
        label: "生效时间",
        type: "datetime",
        width: 33.33,
        value: "",
        id: "enabledTime",
      },
      {
        label: "失效时间",
        type: "datetime",
        width: 33.33,
        value: "",
        id: "disableTime",
        isNeed: false,
      },
      {
        label: "检验项目",
        type: "slot",
        slotName: "table",
        width: 100,
        id: "testProjectList",
        isNeed: false,
      },
    ],
    detailTableColumn: [
      {
        type: "text",
        label: "检验项目",
        value: "projectName",
      },
      {
        type: "text",
        label: "单位",
        value: "newNumUnit",
      },
      {
        type: "text",
        label: "标准数值",
        value: "standardValue",
      },
      {
        type: "text",
        label: "数值区间",
        value: "lowerUpper",
      },
    ],
    detailList: [
      {
        type: "text",
        label: "基础信息",
        list: [
          {
            text: "检验编码",
            id: "standardCode",
            width: 33.33,
          },
          {
            text: "标准名称",
            id: "standardName",
            width: 33.33,
          },
          {
            text: "标准描述",
            id: "remark",
            width: 33.33,
          },
          {
            text: "版本号",
            id: "standardVersion",
            width: 33.33,
          },
          {
            text: "生效时间",
            id: "enabledTime",
            width: 33.33,
          },
          {
            text: "失效时间",
            id: "disableTime",
            width: 33.33,
          },
        ],
      },
      {
        id: "projectName",
        type: "slot",
        slotName: "projectNameTable",
        label: "检验项目",
      },
    ],
    footerList: [
      {
        label: "关闭",
        option: "close",
        color: "blue",
      },
    ],
    detailData: {},

    totalNum: 0,
    isShowDetailPopup: false,
    dialogParams: {
      current: 1,
      size: 10,
    },
    dialogTotal: 0,
    // 物流检验-end

    // 检验标准与物料-start
    standardBtnList: [
      {
        label: "新增",
        option: "standardAdd",
        color: "blue",
      },
      {
        label: "启用",
        option: "standardEnable",
        color: "white",
        isRelaTable: true,
      },
      {
        label: "停用",
        option: "standardStop",
        color: "white",
        isRelaTable: true,
      },
      {
        label: "导出",
        option: "export",
        color: "white",
      },
    ],
    standardTotal: 0,
    standardSearchParams: {
      createStartTime: "",
      createEndTime: "",
      categoryCode: "",
      categoryName: "",
      materialCode: "",
      materialName: "",
      current: 1,
      size: 10,
    },
    standardSearchShowList: [
      {
        id: "materialCategoryId",
        label: "物料类别编码",
        type: "loadselect",
        value: "",
        isShow: true,
        width: 33.3,
        currentErrorLabel: "请选择物料类别编码",
        errorStatus: false,
        selectedLabel: "",
        reviewLabel: "categoryCode",
        requestObj: {
          url: "/api/mes-production-service/material-category/rpc-page",
          method: "post",
          searchKey: "categoryCode",
          rlLabel: "categoryCode",
          rlValue: "id",
          resultKey: "data,data,records",
        },
      },
      {
        id: "materialCategoryId",
        label: "物料类别名称",
        type: "loadselect",
        value: "",
        isShow: true,
        width: 33.3,
        currentErrorLabel: "请选择物料类别名称",
        errorStatus: false,
        selectedLabel: "",
        reviewLabel: "categoryName",
        requestObj: {
          url: "/api/mes-production-service/material-category/rpc-page",
          method: "post",
          searchKey: "categoryName",
          rlLabel: "categoryName",
          rlValue: "id",
          resultKey: "data,data,records",
        },
      },
      {
        id: "materialId",
        label: "物料编码",
        type: "loadselect",
        value: "",
        isShow: true,
        width: 33.3,
        currentErrorLabel: "请选择物料编码",
        errorStatus: false,
        selectedLabel: "",
        reviewLabel: "materialCode",
        defaultParams: { isEnabledList: [1] },
        requestObj: {
          url: "/api/mes-production-service/material/page",
          method: "post",
          searchKey: "materialCode",
          rlLabel: "materialCode",
          rlValue: "id",
          resultKey: "data,data,records",
        },
      },
    ],
    standardSearchHideList: [
      {
        id: "materialId",
        label: "物料名称",
        type: "loadselect",
        value: "",
        isShow: true,
        width: 33.3,
        currentErrorLabel: "请选择物料名称",
        errorStatus: false,
        selectedLabel: "",
        reviewLabel: "materialName",
        defaultParams: { isEnabledList: [1] },
        requestObj: {
          url: "/api/mes-production-service/material/page",
          method: "post",
          searchKey: "materialName",
          rlLabel: "materialName",
          rlValue: "id",
          resultKey: "data,data,records",
        },
      },
      {
        width: 33.3,
      },
      {
        startStr: "createStartTime",
        endStr: "createEndTime",
        id: "createTime",
        type: "daterange",
        width: 80,
        label: "创建时间",
        value: [],
        radio: 1,
        timePeriod: true,
      },
    ],
    standardTableColumn: [
      {
        type: "text",
        label: "物料类别编码",
        value: "materialCategoryCode",
        width: 160,
      },
      {
        type: "text",
        label: "物料类别名称",
        value: "materialCategoryName",
        width: 160,
      },
      {
        type: "text",
        label: "物料编码",
        value: "materialCode",
      },
      {
        type: "text",
        label: "物料名称",
        value: "materialName",
      },
      {
        type: "text",
        label: "标准编码",
        value: "standardCode",
      },
      {
        type: "text",
        label: "标准名称",
        value: "standardName",
      },
      {
        type: "text",
        label: "状态",
        value: "isEnabledName",
      },
      {
        type: "text",
        label: "创建人员",
        value: "createUserName",
      },
      {
        type: "text",
        label: "创建时间",
        value: "createTime",
        width: 160,
      },
      {
        type: "option",
        label: "操作",
        fixed: "right",
        width: 80,
        showBtnList: [
          {
            label: "删除",
            option: "standardDelRow",
          },
        ],
      },
    ],
    standardTableData: [],
    standardIsShowEdit: false,
    standardFormObj: {},
    standardFormData: {},
    standardPopupList: [
      {
        id: "materialCategoryId",
        label: "物料类别编码",
        type: "loadselect",
        value: "",
        isShow: true,
        width: 100,
        currentErrorLabel: "请选择单位",
        errorStatus: false,
        selectedLabel: "",
        reviewLabel: "categoryCode",
        defaultParams: {},
        requestObj: {
          url: "/api/mes-production-service/material-category/page",
          method: "post",
          searchKey: "categoryCode",
          rlLabel: "categoryCode",
          rlValue: "id",
          resultKey: "data,data,records",
        },
      },
      {
        label: "物料类别名称",
        type: "input",
        width: 100,
        value: "",
        id: "materialCategoryName",
        disabled: true,
      },
      {
        id: "materialId",
        label: "物料编码",
        type: "loadselect",
        value: "",
        isShow: true,
        width: 100,
        currentErrorLabel: "请选择物料编码",
        errorStatus: false,
        selectedLabel: "",
        reviewLabel: "materialCode",
        defaultParams: { isEnabledList: [1] },
        disabled: false,
        requestObj: {
          url: "/api/mes-production-service/material/rpc-page",
          method: "post",
          searchKey: "materialCode",
          rlLabel: "materialCode",
          rlValue: "id",
          resultKey: "data,data,records",
        },
      },
      {
        label: "物料名称",
        type: "input",
        width: 100,
        value: "",
        id: "materialName",
        isNeed: false,
        disabled: true,
      },
      {
        id: "standardId",
        label: "标准编码",
        type: "loadselect",
        value: "",
        isShow: true,
        width: 100,
        currentErrorLabel: "请选择单位",
        errorStatus: false,
        selectedLabel: "",
        reviewLabel: "standardCode",
        defaultParams: { standardStatusList: [2] },
        requestObj: {
          url: "/api/mes-quality-service/standard/page",
          method: "post",
          searchKey: "standardCode",
          rlLabel: "standardCode",
          rlValue: "id",
          resultKey: "data,data,records",
        },
      },
      {
        label: "标准名称",
        type: "input",
        width: 100,
        value: "",
        id: "standardName",
        disabled: true,
      },
    ],
    // 联动
    relationList: [
      {
        id: "materialCategoryId",
        relaList: [
          {
            relaId: "materialCategoryName",
            relaValue: "categoryName",
            reviewValue: "categoryName",
            disabled: true,
          },
          {
            relaId: "materialId",
            isNotStrict: true,
            params: [
              {
                labelWord: "materialCategoryId",
                realWord: "rlValue",
              },
            ],
          },
        ],
      },
      {
        id: "materialId",
        relaList: [
          {
            relaId: "materialName",
            relaValue: "materialName",
            reviewValue: "materialName",
            disabled: true,
          },
          {
            relaId: "materialCategoryId",
            isNotStrict: true,
            params: [
              {
                labelWord: "materialCategoryId",
                realWord: "materialCategoryId",
              },
            ],
          },
        ],
      },
      {
        id: "standardId",
        relaList: [
          {
            relaId: "standardName",
            relaValue: "standardName",
            reviewValue: "standardName",
            disabled: true,
          },
        ],
      },
    ],
    // 检验标准与物料-end
  }),
  watch: {
    "inlayForm.testType": {
      immediate: true,
      handler(newVal) {
        this.testTypeChange(newVal);
      },
    },
    tableAddData: {
      deep: true,
      handler() {
        this.handlerPageChange();
      },
    },
  },
  computed: {
    ids() {
      return this.$refs.trTable.selectionList.map((item) => item.id);
    },
    standardIds() {
      return this.$refs.trStandardTable.selectionList.map((item) => item.id);
    },
    isAdd() {
      return this.currentHandle == "add" ? true : false;
    },
    tableAddDataList() {
      return this.isAdd ? this.tableAddDataCopy : this.tableAddData;
    },
  },
  methods: {
    testTypeChange(newVal) {
      const standardValueObj = this.$findByProperty(
        this.inlayPopupList,
        "id",
        "standardValue"
      );
      const numValueObj = this.$findByProperty(
        this.inlayPopupList,
        "id",
        "numValue"
      );
      const unitCodeObj = this.$findByProperty(
        this.inlayPopupList,
        "id",
        "unitCode"
      );
      unitCodeObj.errorStatus = false;
      if (newVal == 1) {
        standardValueObj.isShow = true;
        numValueObj.isShow = true;
        unitCodeObj.isNeed = true;
      } else {
        standardValueObj.isShow = false;
        numValueObj.isShow = false;
        unitCodeObj.isNeed = false;
        this.inlayForm.standardValue = null;
        this.inlayForm.valueUpper = null;
        this.inlayForm.valueLower = null;
      }
    },
    exportHandle() {
      this.$exportHandle({
        vm: this,
        params: this.searchParams,
        code: "material",
      });
    },
    standardExportHandle() {
      this.$exportHandle({
        vm: this,
        params: this.standardSearchParams,
        code: "standard",
      });
    },
    // standardSelectChange() {
    // const cloneList = this.$refs.standardRef?.$refs.trEdit?.cloneList;
    // if (val.ftId == "materialCategoryId") {
    //   const materialCategoryId = val.rlValue;
    //   const materialIdObj = cloneList?.find(
    //     (item) => item.id == "materialId"
    //   );
    //   const materialNameObj = cloneList?.find(
    //     (item) => item.id == "materialName"
    //   );
    //   if (!materialIdObj) return;
    //   materialIdObj.disabled = false;
    //   materialIdObj.defaultParams = {
    //     ...materialIdObj.defaultParams,
    //     materialCategoryId,
    //   };
    //   materialNameObj.value = "";
    //   materialIdObj.value = "";
    // }
    // if (val.ftId == "materialId") {
    //   const materialNameObj = cloneList?.find(
    //     (item) => item.id == "materialName"
    //   );
    //   materialNameObj.value = val.materialName;
    // }
    // },
    paginateArray(list, current, size) {
      const totalPages = Math.ceil(list.length / size);

      if (current < 1 || current > totalPages)
        return { result: [], currentList: [] };

      const startIndex = (current - 1) * size;

      const currentList = list.slice(startIndex, startIndex + size);
      const result = Array.from({ length: totalPages }, (_, index) =>
        list.slice(index * size, (index + 1) * size)
      );

      return { result, currentList };
    },
    async standardUpdateStatus(isEnabled) {
      const testStr = isEnabled == 1 ? "启用" : "停用";
      await this.$textShow({
        title: this.$t("tip.label"),
        content: [`是否确认${testStr}？`],
      });
      await standardUpdateStatus({ idList: this.standardIds, isEnabled });
      await this.getStandardList();
      this.$message.success(this.$t("msg.success"));
    },
    async standardDelRow(row) {
      await this.$textShow({
        title: this.$t("tip.label"),
        content: [this.$t("tip.delete")],
      });
      await standardMaterialDelete({ ids: [row.id] });
      await this.getStandardList();
      this.$message.success(this.$t("msg.success"));
    },
    async standardMaterialSave() {
      this.standardFormObj.isEnabled = 1;
      await standardMaterialSave(this.standardFormObj);
      await this.getStandardList();
      this.$message.success(this.$t("msg.success"));
      this.standardIsShowEdit = false;
    },
    async getDetectCategoryList() {
      let res = await this.$fetchEnumData([enumData.detectCategory]);
      const testTypeObj = this.$findByProperty(
        this.inlayPopupList,
        "id",
        "testType"
      );
      testTypeObj.list = res[enumData.detectCategory];
    },
    async getInspectionStatus() {
      let res = await this.$fetchEnumData([enumData.inspectionStatus]);
      const testTypeObj = this.$findByProperty(
        this.searchHideList,
        "id",
        "standardStatusList"
      );
      testTypeObj.list = res[enumData.inspectionStatus];
    },
    // 物料检验标准新增-请求 standardStatus：1：草稿 2启用, 3停用
    async materialSave(standardStatus) {
      const texts = ["暂存", "保存"];
      await this.$textShow({
        title: this.$t("tip.label"),
        content: [`是否确认${texts[standardStatus - 1]}?`],
      });

      const listKey = [
        "projectName",
        "remark",
        "standardValue",
        "testType",
        "unitCode",
        "valueLower",
        "valueUpper",
        "unitId",
      ];

      const testProjectList = this.tableAddData.map((item) =>
        Object.fromEntries(listKey.map((key) => [key, item[key]]))
      );
      const axiosObj = {
        ...this.formObj,
        testProjectList: this.isAdd ? testProjectList : [],
        standardStatus,
        id: this.dialogId,
      };

      this.$validateData(axiosObj, 3);

      this.isAdd
        ? await materialSave(axiosObj)
        : await dialogAddUpdate(axiosObj);
      await this.getTableList();
      this.addClose();
      this.$message.success(this.$t("msg.success"));
    },
    materialTreeAdd() {
      this.currentType = "add";
      this.inlayCheckTitle = "新增";
      this.isShowEditInlay = true;
    },
    async delRowMaterialAdd(val) {
      await this.$textShow({
        title: this.$t("tip.label"),
        content: [`是否确认删除？`],
      });
      if (this.isAdd) {
        const indexFind = this.tableAddData.findIndex(
          (item) => item.id == val.id
        );
        if (indexFind == -1) return;
        this.tableAddData.splice(indexFind, 1);
        this.handlerPageChange();
      } else {
        await dialogDelete({ ids: [val.id] });
        this.getDialogPage();
      }
    },
    editRowMaterialAdd(val) {
      this.currentType = "edit";
      this.inlayCheckTitle = "编辑";
      this.$validateData(val, 3);
      this.inlayForm = val;
      const unitCodeObj = this.$findByProperty(
        this.inlayPopupList,
        "id",
        "unitCode"
      );
      if (unitCodeObj)
        unitCodeObj.selectedLabel = `${val.unitCode}(${val.unitName})`;
      this.isShowEditInlay = true;
    },
    inlaySubmitVerify() {
      let isEmptys = [];
      this.inlayPopupList.forEach((item) => {
        if (item.type == "interval") {
          item.errorStatus = false;
          return isEmptys.push(true);
        }
        if (item.type == "input")
          return isEmptys.push(this.changeVerify(item.id, item));
        if (item.isNeed === false) {
          item.errorStatus = false;
          return isEmptys.push(true);
        }

        const isEmpty = [null, undefined, ""].includes(this.inlayForm[item.id]);
        if (isEmpty) {
          item.errorStatus = true;
        } else {
          item.errorStatus = false;
        }
        isEmptys.push(!isEmpty);
      });
      return !isEmptys.includes(false);
    },
    inlayNumVerify() {
      if (this.inlayForm.testType == 2) return true;

      const nullList = [undefined, null, ""];
      const standardValue = nullList.includes(this.inlayForm.standardValue);
      const valueUpper = nullList.includes(this.inlayForm.valueUpper);
      const valueLower = nullList.includes(this.inlayForm.valueLower);
      const twoValueNull = valueUpper && valueLower;
      const threeNull = standardValue && twoValueNull;
      if (threeNull) {
        this.$message.warning("标准数值和数值区间不能同时为空！");
        return false;
      }
      if (!twoValueNull) {
        const lower = parseFloat(this.inlayForm.valueLower);
        const upper = parseFloat(this.inlayForm.valueUpper);
        if (lower >= upper) {
          this.$message.warning("数值上限值必须大于数值下限值");
          return false;
        } else if (lower < 0) {
          this.$message.warning("数值下限不能小于0");
          return false;
        } else if (upper < 0) {
          this.$message.warning("数值上限不能小于0");
          return false;
        }
      }
      if (parseFloat(this.inlayForm.standardValue) < 0) {
        this.$message.warning("标准数值不能小于0");
        return false;
      }

      if (standardValue && (valueUpper || valueLower)) {
        this.$message.warning("数值区间的数值下限或数值上限不能为空！");
        return false;
      }
      if (!standardValue) {
        if (twoValueNull) return true;
        if (valueUpper || valueLower) {
          this.$message.warning("数值区间的数值下限或数值上限不能为空！");
          return false;
        }
      }
      return true;
    },
    changeVerify(prop, obj) {
      if (obj.isNeed === false) {
        obj.errorStatus = false;
        return true;
      }
      const isEmpty = [null, undefined, ""].includes(this.inlayForm[prop]);
      obj.errorStatus = isEmpty;
      return !isEmpty;
    },
    changeSelectHandle(obj, event) {
      if (obj.id == "unitCode") {
        this.inlayForm.unitCode = event.rlLabel;
        this.inlayForm.unitId = event.rlValue;
        this.inlayForm.u9Code = event.u9Code;
        console.log(event, "=");
      }
      this.changeVerify(obj.id, obj);
    },
    async getTableList() {
      const { data: res } = await getList(this.searchParams);
      this.$validateData(res.data.records);
      this.materialTableData = res.data.records;
      this.materialTableData.forEach((item) => {
        item["standardStatusNameColor"] =
          {
            1: "#999999",
            2: "#00A870",
            3: "#E34D59",
          }[item.standardStatus] || "";
      });
      this.totalNum = res.data.total;
      this.$refs.trTable.clearSelect();
    },
    async getStandardList() {
      const { data: res } = await getStandardList(this.standardSearchParams);
      this.$validateData(res.data.records);
      this.standardTableData = res.data.records;
      this.standardTableData.forEach((item) => {
        item["isEnabledNameColor"] =
          {
            1: "#00A870",
            0: "#E34D59",
          }[item.isEnabled] || "";
      });
      this.standardTotal = res.data.total;
      this.$refs.trStandardTable.clearSelect();
    },
    searchHandle() {
      this.getTableList();
    },
    standardSearchHandle() {
      this.getStandardList();
    },
    tagHandle(tagObj) {
      if (!tagObj) return;
      this.tagVal = tagObj.value;
    },
    materialAddFun() {
      this.isShowEdit = true;
      this.checkTitle = "新增";
      this.currentHandle = "add";
    },
    async materialUpdateStatus(standardStatus) {
      const testStr = standardStatus == 2 ? "启用" : "停用";
      await this.$textShow({
        title: this.$t("tip.label"),
        content: [`是否确认${testStr}？`],
      });
      await materialUpdateStatus({ idList: this.ids, standardStatus });
      await this.getTableList();
      this.$message.success(this.$t("msg.success"));
    },
    async delRowMaterial(row) {
      await this.$textShow({
        title: this.$t("tip.label"),
        content: [this.$t("tip.delete")],
      });
      await materialDelete({ testStandardId: row.id });
      await this.getTableList();
      this.$message.success(this.$t("msg.success"));
    },
    async editRowMaterial(row) {
      this.checkTitle = "编辑";
      this.currentHandle = "edit";
      this.$validateData(row, 3);
      this.formData = row;
      this.dialogId = row.id;
      const editData = await this.getDialogPage();
      this.formData = editData;
      this.isShowEdit = true;
    },
    async copyRowMaterial(row) {
      this.checkTitle = "新增";
      this.currentHandle = "copy";
      this.dialogId = row.id;
      this.$validateData(row, 3);
      await this.getDialogPage(true);
      this.isShowEdit = true;
    },
    async viewRowMaterial(row = {}) {
      this.dialogId = row.id || this.dialogId;

      this.currentHandle = "edit";
      const detaliData = await this.getDialogPage();
      this.$validateData(detaliData);
      this.detailData = {
        ...detaliData,
        newNumUnit: `${detaliData.unitCode}(${detaliData.unitName})`,
      };
      this.isShowDetailPopup = true;
    },
    inlayClose() {
      this.isShowEditInlay = false;
      Object.keys(this.inlayForm).forEach((key) => {
        this.$set(this.inlayForm, key, null);
        this.inlayForm.testType = 2;
      });
      const unitCodeObj = this.$findByProperty(
        this.inlayPopupList,
        "id",
        "unitCode"
      );
      if (unitCodeObj) unitCodeObj.selectedLabel = "";
      this.inlayPopupList.forEach((item) => (item.errorStatus = false));
      if (this.isAdd) this.handlerPageChange();
    },
    async confrimHandle() {
      const [verify1, verify2] = [
        this.inlaySubmitVerify(),
        this.inlayNumVerify(),
      ];
      if (!verify1 || !verify2) return;

      const textStr = this.currentType == "add" ? "保存" : "编辑";
      await this.$textShow({
        title: this.$t("tip.label"),
        content: [`是否确认${textStr}`],
      });
      const lowerUpper = `${this.inlayForm.valueLower}~${this.inlayForm.valueUpper}`;

      const handlerData = {
        ...this.inlayForm,
        lowerUpper: this.inlayForm.valueLower ? lowerUpper : "-",
        id: this.currentType == "add" ? Date.now() : this.inlayForm.id,
        testStandardId: this.dialogId,
        newNumUnit: this.inlayForm.unitCode,
        unitCode: this.inlayForm.u9Code,
      };
      console.log(handlerData, "======handlerData=handlerData");
      this.$validateData(handlerData);

      const editFun = async () => {
        if (this.isAdd) {
          const index = this.tableAddData.findIndex(
            (item) => item.id === handlerData.id
          );
          if (index !== -1) {
            this.tableAddData.splice(index, 1, handlerData);
          }
        } else {
          this.$validateData(handlerData, 3);
          await dialogUpdate(handlerData);
          this.getDialogPage();
        }
      };

      const addFun = async () => {
        if (this.isAdd) {
          this.tableAddData.push(handlerData);
        } else {
          this.$validateData(handlerData, 3);
          await dialogSave(handlerData);
          this.getDialogPage();
        }
      };

      this.currentType == "add" ? await addFun() : await editFun();

      this.isShowEditInlay = false;
      this.inlayClose();
      this.$message.success(this.$t("msg.success"));
    },
    addClose() {
      this.isShowEdit = false;
      this.tableAddData = [];
      this.tableAddDataCopy = [];
      this.currentHandle = "";
      this.dialogParams = {
        current: 1,
        size: 10,
      };
      this.dialogTotal = 0;
      this.formData = {};
    },
    async standardConfrimHandle() {
      await this.$textShow({
        title: this.$t("tip.label"),
        content: ["是否确认保存？"],
      });
      this.standardMaterialSave();
    },
    detailHandle() {
      this.viewRowMaterial();
    },
    // type:copy-复制，edit-编辑
    async getDialogPage(isCopy) {
      const axiosObj = {
        ...this.dialogParams,
        testStandardId: this.dialogId,
      };
      const { data: res } = isCopy
        ? await getDialogCopy(axiosObj)
        : await getDialogPage(axiosObj);
      const records = res.data.projectPageResp.records;
      this.$validateData(records);
      this.dialogId = res.data.id;
      records.forEach((item) => {
        item.lowerUpper = `${item.valueLower}~${item.valueUpper}`;
        item.newNumUnit = `${item.unitCode}(${item.unitName})`;
      });

      this.tableAddData = records;

      this.dialogTotal = res.data.projectPageResp.total;
      return res.data;
    },
    dialogHandle() {
      if (this.isAdd) return this.handlerPageChange();
      this.getDialogPage();
    },
    handlerPageChange() {
      if (!this.isAdd) return;
      this.dialogTotal = this.tableAddData.length;
      const pageObj = this.paginateArray(
        this.tableAddData,
        this.dialogParams.current,
        this.dialogParams.size
      );
      this.tableAddDataCopy = pageObj.currentList;
    },
  },
  mounted() {
    // this.getTableList();
    // this.getStandardList();
    this.getDetectCategoryList();
    this.getInspectionStatus();
  },
};
</script>

<style lang="scss" scoped>
::v-deep.page-container {
  input::-webkit-outer-spin-button,
  input::-webkit-inner-spin-button {
    -webkit-appearance: none;
  }
  input[type="number"] {
    -moz-appearance: textfield;
  }
}
.handoff {
  display: flex;
  border-radius: 4px;
  color: rgba(0, 0, 0, 0.4);
  margin-bottom: 16px;
  & > div {
    background-color: #ffffff;
    padding: 4px 16px;
    font-weight: 400;
    font-size: 14px;
    cursor: pointer;
    box-sizing: border-box;
  }
  & > div:nth-child(1) {
    border-top-left-radius: 4px;
    border-bottom-left-radius: 4px;
  }
  & > div:nth-child(2) {
    border-top-right-radius: 4px;
    border-bottom-right-radius: 4px;
  }
  .selected {
    color: #0087d6;
    border: 1px solid #0087d6;
    border-radius: 4px;
  }
}

.el-date-editor--datetimerange {
  width: auto;
}
.edit-list-wrap {
  display: flex;
  flex-wrap: wrap;
  overflow-y: scroll;
  overflow-x: hidden;
  margin-right: -12px;
  padding-right: 12px;
  .edit-list-left {
    position: relative;
    flex: 1;
    display: flex;
    flex-wrap: wrap;
    margin-right: -24px;
  }
  .edit-list-right {
    height: 8px;
  }
  .edit-item-wrap {
    display: flex;
    align-items: center;
    padding-right: 24px;
    margin-bottom: 24px;
    .edit-label {
      flex-shrink: 0;
      padding-left: 8px;
      .edit-text {
        width: 100%;
        color: rgba(#000, 0.9);
        font-weight: 400;
        font-size: 14px;
        padding-right: 16px;
        text-align: right;
        .before {
          position: relative;
          &::before {
            position: absolute;
            content: "*";
            color: #e34d59;
            top: 3px;
            left: -8px;
          }
        }
      }
    }
    .edit-item-right {
      position: relative;
      flex: 1;
      .check-box {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        margin-bottom: -16px;
        .check-item {
          display: flex;
          align-items: center;
          margin-right: 16px;
          margin-bottom: 16px;
          cursor: pointer;
          &:last-child {
            margin-right: 0;
          }
        }

        .check-icon {
          height: 16px;
          width: 16px;
          margin-right: 8px;
          border-radius: 3px;
          border: 1px solid #dcdcdc;
        }

        .check-icon.active {
          border: 1px solid $main-color;
          background-color: $main-color;
          background-image: url("~@/assets/icons/check_active_icon.png");
          background-size: contain;
        }
        .check-label {
          color: rgba(#000, 0.9);
          font-weight: 400;
          font-size: 14px;
          white-space: nowrap;
        }
      }
      .edit-error-label {
        opacity: 0;
        transition: opacity 0.3s;
        position: absolute;
        font-size: 12px;
        top: 110%;
        font-weight: 400;
        color: #e34d59;
        left: 8px;
      }
      &.errorStatus {
        .edit-error-label {
          opacity: 1;
        }
      }
    }
    &.flexStart {
      align-items: flex-start;
      .edit-label {
        padding-top: 6px;
      }
    }
    &.unNeed {
      .before::before {
        display: none;
      }
    }
  }
}

.edit-interval {
  display: flex;
  align-items: center;
  .lever {
    color: #000000;
    font-weight: 400;
    font-size: 14px;
    width: 22px;
    border-bottom: 1px solid rgba(0, 0, 0, 0.9);
    margin: 0 4px;
  }
}
</style>
